package com.chenix.aicodehelper.Tools;

import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class MSNWeatherTool {

    // 和风天气 API Host，例如 "https://abcxyz.qweatherapi.com"
    //https://abcxyz.qweatherapi.com
    private static final String API_HOST = "https://devapi.qweather.com";
    // 和风天气 API Key（在和风天气控制台申请）
    private static final String API_KEY = "41e89f4c011845e3a0d9dcf8ff122e3a";

    /**
     * 获取天气信息
     * @param days now / 3d / 7d 等
     * @param location 城市ID，例如 101010100（北京）
     * @return 天气文本
     */
    @Tool(name = "QWeatherSearch", value = "Retrieves weather info from QWeather API using location ID and days.")
    public String searchWeather(
            @P(value = "days (now, 3d, 7d)") String days,
            @P(value = "location ID (e.g. 101010100)") String location) {

        if (days == null || days.isEmpty() || location == null || location.isEmpty()) {
            return "错误：days 和 location 参数不能为空";
        }

        try {
            String urlStr = String.format("%s/v7/weather/now?location=%s&key=%s",
                    API_HOST, days, location, API_KEY);

            HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");
            conn.setRequestProperty("Accept-Encoding", "gzip");

            if (conn.getResponseCode() != 200) {
                return "获取天气信息失败，HTTP 状态码：" + conn.getResponseCode();
            }

            // 读取返回数据
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)
            );
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            return parseWeatherJson(days, response.toString());

        } catch (Exception e) {
            return "调用和风天气 API 失败：" + e.getMessage();
        }
    }

    /**
     * 解析和风天气返回的JSON
     */
    private String parseWeatherJson(String days, String jsonStr) {
        JSONObject json = new JSONObject(jsonStr);
        if (!"200".equals(json.optString("code"))) {
            return "和风天气返回错误：" + json.optString("code");
        }

        StringBuilder sb = new StringBuilder();
        sb.append("更新时间：").append(json.optString("updateTime")).append("\n");

        if ("now".equalsIgnoreCase(days)) {
            JSONObject now = json.optJSONObject("now");
            if (now != null) {
                sb.append("温度：").append(now.optString("temp")).append("°C\n")
                        .append("天气：").append(now.optString("text")).append("\n")
                        .append("风向：").append(now.optString("windDir")).append("\n")
                        .append("湿度：").append(now.optString("humidity")).append("%");
            }
        } else {
            JSONArray daily = json.optJSONArray("daily");
            if (daily != null) {
                for (int i = 0; i < daily.length(); i++) {
                    JSONObject day = daily.getJSONObject(i);
                    sb.append(day.optString("fxDate")).append("：")
                            .append(day.optString("textDay")).append(" / 夜间：")
                            .append(day.optString("textNight")).append("，")
                            .append("最高温 ").append(day.optString("tempMax")).append("°C，")
                            .append("最低温 ").append(day.optString("tempMin")).append("°C\n");
                }
            }
        }
        return sb.toString().trim();
    }
}
